package com.pur.zsms.supplier.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.cglib.beans.BeanCopier;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.pur.zsms.accountmanage.vo.AccountVo;
import com.pur.zsms.check.vo.CheckVo;
import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.common.util.ExcelReader;
import com.pur.zsms.common.util.FileUtill;
import com.pur.zsms.common.util.PubFun;
import com.pur.zsms.common.vo.CommonType;
import com.pur.zsms.documentsmanage.vo.DomVo;
import com.pur.zsms.lockmanage.service.ILockTransService;
import com.pur.zsms.matermanage.mater.vo.MaterVo;
import com.pur.zsms.matermanage.mater.vo.MaterVoForCostSupplier;
import com.pur.zsms.matermanage.mater.vo.MaterVoForSup;
import com.pur.zsms.matermanage.mater.vo.OrderDistributorMaterRealVo;
import com.pur.zsms.note.service.INoteService;
import com.pur.zsms.ordercustommanage.po.OrderDistributorMaterRealPo;
import com.pur.zsms.ordercustommanage.po.OrderDistributorPo;
import com.pur.zsms.ordercustommanage.po.OrderSupplierMaterPo;
import com.pur.zsms.ordercustommanage.po.OrderSupplierPo;
import com.pur.zsms.ordercustommanage.service.ISelectFoodService;
import com.pur.zsms.ordercustommanage.service.InsertCusFoodService;
import com.pur.zsms.ordercustommanage.vo.ExcelVo;
import com.pur.zsms.ordercustommanage.vo.OrderCustVo;
import com.pur.zsms.ordercustommanage.vo.OrderDistributorVo;
import com.pur.zsms.ordercustommanage.vo.OrderSupplierMaterRealVo;
import com.pur.zsms.ordercustommanage.vo.OrderSupplierMaterVo;
import com.pur.zsms.ordercustommanage.vo.OrderSupplierMaterVoFooter;
import com.pur.zsms.ordercustommanage.vo.OrderSupplierVo;
import com.pur.zsms.ordercustommanage.vo.OrderSupplierVoFooter;
import com.pur.zsms.ordercustommanage.vo.SelectMaterVo;
import com.pur.zsms.pmsnmanage.menu.po.MenuPo;
import com.pur.zsms.pmsnmanage.role.vo.RoleVo;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.pmsnmanage.user.po.UserRolePo;
import com.pur.zsms.pmsnmanage.user.service.IUserService;
import com.pur.zsms.pmsnmanage.user.vo.UserVo;
import com.pur.zsms.pmsnmanage.user.web.UserControllor;
import com.pur.zsms.service.IDistributorService;
import com.pur.zsms.shopmanage.po.ShopPo;
import com.pur.zsms.shopmanage.service.IShopService;
import com.pur.zsms.storemanage.po.StoreInPo;
import com.pur.zsms.storemanage.po.StoreOutPo;
import com.pur.zsms.storemanage.service.IStoreService;
import com.pur.zsms.storemanage.vo.StoreInVo;
import com.pur.zsms.storemanage.vo.StoreOutVo;
import com.pur.zsms.supplier.po.ShopSupplierTypePo;
import com.pur.zsms.supplier.po.SupplierPo;
import com.pur.zsms.supplier.service.ISupplierOrderService;
import com.pur.zsms.supplier.service.ISupplierService;
import com.pur.zsms.supplier.vo.ShopSupplierVo;
import com.pur.zsms.supplier.vo.SupplierDistributeVo;
import com.pur.zsms.supplier.vo.SupplierOrderCustVo;
import com.pur.zsms.supplier.vo.SupplierQualificationVo;
import com.pur.zsms.supplier.vo.SupplierVo;
import com.pur.zsms.systemsetting.datadictionary.po.Code;
import com.pur.zsms.systemsetting.datadictionary.vo.CodeVo;
import com.pur.zsms.timecontrol.service.ITimeControlService;
import com.pur.zsms.weixin.service.IWeixinService;

/**
 * 供应商控制器
 * 
 * @author yuxin
 * 
 */
@Controller
@RequestMapping(value = "/distributor")
public class DistributorController {
	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(DistributorController.class);
	protected int page = 1;

	protected int pageSize = 15;

	PaginationSupport pageList;

	final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	@Resource(name = "weixinService")
	private IWeixinService weixinService;

	@Resource(name = "supplierService")
	private ISupplierService supplierService;

	@Resource(name = "distributorService")
	private IDistributorService distributorService;

	@Resource(name = "timeControlService")
	private ITimeControlService timeControlService;

	@Resource(name = "userService")
	private IUserService userService;

	@Resource(name = "lockTransService")
	private ILockTransService lockTransService;

	@Resource(name = "storeService")
	private IStoreService storeService;

	@Resource(name = "shopService")
	private IShopService shopService;

	@Resource(name = "noteService")
	private INoteService noteService;

	@Resource(name = "selectFoodService")
	private ISelectFoodService selectFoodService;

	@Resource(name = "insertCusFoodService")
	private InsertCusFoodService insertCusFoodService;

	@Resource(name = "supplierOrderService")
	private ISupplierOrderService supplierOrderService;

	@RequestMapping(value = "/findMaterForDistributor.do", method = { RequestMethod.POST })
	@ResponseBody
	public String findMaterForDistributor(@RequestParam(required = false) String page, @RequestParam(required = false) String rows, MaterVo materVo,
			HttpSession session) throws GenericException {
		JSONObject json = new JSONObject();
		UserPo userInfo = (UserPo) session.getAttribute("user");
		materVo.setSupId(supplierService.getSupIdByUserId(userInfo.getUserId()));
		if (page == null || page.equals(""))
			page = "1";
		if (rows == null || rows.equals(""))
			rows = "10";
		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));
		this.pageList = distributorService.findMaterForDistributor(pageController, materVo);
		List<MaterVo> materList = new ArrayList<MaterVo>();
		List items = pageList.getItems();
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				MaterVo f = new MaterVo();
				f.setMaterId((Integer) item[0]);
				f.setMaterName((String) item[1]);
				f.setMaterType((Integer) item[2]);
				f.setUnit((String) item[3]);
				f.setSpecifications((String) item[4]);
				f.setBrands((String) item[5]);
				f.setMaterStoreNumber((BigDecimal) item[6]);
				f.setMaterLevel((Integer) item[7]);
				materList.add(f);
			}
		}
		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", materList);
		return json.toString();
	}

	/**
	 * 选择材料
	 * */
	@RequestMapping(value = "/commitMaterOrderForDistributor.do", method = { RequestMethod.POST })
	@ResponseBody
	public String commitMaterOrderForDistributor(OrderDistributorMaterRealVo orderDistributorMaterRealVo, HttpSession session) {

		UserPo userInfo = (UserPo) session.getAttribute("user");
		JSONObject json1 = new JSONObject();
		String nowTime = PubFun.getCurrentDate() + " " + PubFun.getCurrentTime();

		try {
			long ordDistributorId = supplierService.getSupIdByUserId(userInfo.getUserId());
			orderDistributorMaterRealVo.setOrdDistributorId(ordDistributorId);

			// 增加校验 每天只能提交一次采购清单-----------下
			// int ordId = 0;
			/*
			 * int ordId =
			 * selectFoodService.checkCommitMaterOrderForSup(selectMaterVo
			 * .getOrderDate(), shopId, supId); if (ordId != 0) {
			 * json1.put("success", false); json1.put("msg",
			 * selectFoodService.getMsg()); return json1.toString(); }
			 */
			// 增加校验 每天只能提交一次采购清单-----------上

			// 根据日期取得星期几-----------下
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date date = null;
			date = format.parse(orderDistributorMaterRealVo.getOrderDate());
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
			if (dayOfWeek < 0)
				dayOfWeek = 0;
			orderDistributorMaterRealVo.setOrderDay(dayNames[dayOfWeek]);
			// 根据日期取得星期几-----------上
			JSONArray array = JSONArray.fromObject(orderDistributorMaterRealVo.getMaterdategridList());

			List<OrderDistributorMaterRealVo> orderDistributorMaterRealVoList = new ArrayList<OrderDistributorMaterRealVo>();
			for (int i = 0; i < array.size(); i++) {
				JSONObject object = JSONObject.fromObject(array.get(i));
				OrderDistributorMaterRealVo tOrderDistributorMaterRealVo = new OrderDistributorMaterRealVo();
				tOrderDistributorMaterRealVo.setOrdMaterId(Integer.valueOf(object.get("ordMaterId").toString()));
				tOrderDistributorMaterRealVo.setOrdMaterWeight(new BigDecimal(object.get("materWeight").toString()));
				tOrderDistributorMaterRealVo.setOrdMaterWeightReality(new BigDecimal(object.get("materWeight").toString()));
				tOrderDistributorMaterRealVo.setOrdMaterLevel(Integer.valueOf(object.get("materLevel").toString()));
				tOrderDistributorMaterRealVo.setCode(object.get("code").toString());
				tOrderDistributorMaterRealVo.setOrdSupId(orderDistributorMaterRealVo.getOrdSupId());
				tOrderDistributorMaterRealVo.setOrdDistributorId(ordDistributorId);
				tOrderDistributorMaterRealVo.setOrderDate(orderDistributorMaterRealVo.getOrderDate());
				tOrderDistributorMaterRealVo.setOrderDay(orderDistributorMaterRealVo.getOrderDay());
				orderDistributorMaterRealVoList.add(tOrderDistributorMaterRealVo);
			}
			// 先判断 存在不存在此供货商的ordID

			// 往客户订单表中插入值
			// ordId =
			// selectFoodService.checkCommitMaterOrder(selectMaterVo.getOrderDate(),
			// shopId, 0);
			OrderDistributorPo orderDistributorPo = distributorService.addMaterOrderForDistributor(orderDistributorMaterRealVoList);

			distributorService.addMaterOrderDetailForDistributor(orderDistributorMaterRealVoList, orderDistributorPo.getOrdId());
			List<UserPo> userPoList = userService.getUserForSup(orderDistributorPo.getOrdSupId());
			for (UserPo userPo : userPoList) {
				if (userPo.getOpenId() != null && !userPo.getOpenId().equals("")) {
					weixinService.send_template_message_for_commitMaterOrderForDistributor("wx64bdfb1d6682c965", "84b1db883fbb66d23fd959ba418d2e38",
							userPo.getOpenId(), orderDistributorPo);
				}
			}
			/*
			 * noteService.sendMessageToSup(String.valueOf(ordId),
			 * orderDistributorMaterRealVo.getOrderDate(),
			 * shopService.getShopPo(shopId) .getShopName());
			 */
			json1.put("success", true);
		} catch (Exception e) {
			log.info(e.toString());
			json1.put("success", false);
			json1.put("msg", e.getMessage());
		}
		return json1.toString();
	}

	/**
	 * 选择材料 临时加货
	 * */
	@RequestMapping(value = "/commitMaterOrderForDistributorForUpdate.do", method = { RequestMethod.POST })
	@ResponseBody
	public String commitMaterOrderForDistributorForUpdate(OrderDistributorMaterRealVo orderDistributorMaterRealVo, HttpSession session) {

		UserPo userInfo = (UserPo) session.getAttribute("user");
		JSONObject json1 = new JSONObject();
		String nowTime = PubFun.getCurrentDate() + " " + PubFun.getCurrentTime();

		try {
			long ordDistributorId = supplierService.getSupIdByUserId(userInfo.getUserId());
			orderDistributorMaterRealVo.setOrdDistributorId(ordDistributorId);

			// 增加校验 每天只能提交一次采购清单-----------下
			/*
			 * int ordId =
			 * selectFoodService.checkCommitMaterOrderForSup(selectMaterVo
			 * .getOrderDate(), shopId, supId); if (ordId != 0) {
			 * json1.put("success", false); json1.put("msg",
			 * selectFoodService.getMsg()); return json1.toString(); }
			 */
			// 增加校验 每天只能提交一次采购清单-----------上

			// 根据日期取得星期几-----------下
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date date = null;
			date = format.parse(orderDistributorMaterRealVo.getOrderDate());
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
			if (dayOfWeek < 0)
				dayOfWeek = 0;
			orderDistributorMaterRealVo.setOrderDay(dayNames[dayOfWeek]);
			// 根据日期取得星期几-----------上
			JSONArray array = JSONArray.fromObject(orderDistributorMaterRealVo.getMaterdategridList());

			List<OrderDistributorMaterRealVo> orderDistributorMaterRealVoList = new ArrayList<OrderDistributorMaterRealVo>();
			for (int i = 0; i < array.size(); i++) {
				JSONObject object = JSONObject.fromObject(array.get(i));
				OrderDistributorMaterRealVo tOrderDistributorMaterRealVo = new OrderDistributorMaterRealVo();
				tOrderDistributorMaterRealVo.setOrdMaterId(Integer.valueOf(object.get("ordMaterId").toString()));
				tOrderDistributorMaterRealVo.setOrdMaterWeight(new BigDecimal(object.get("materWeight").toString()));
				tOrderDistributorMaterRealVo.setOrdMaterLevel(Integer.valueOf(object.get("materLevel").toString()));
				tOrderDistributorMaterRealVo.setCode(object.get("code").toString());
				tOrderDistributorMaterRealVo.setOrdSupId(orderDistributorMaterRealVo.getOrdSupId());
				tOrderDistributorMaterRealVo.setOrdDistributorId(ordDistributorId);
				tOrderDistributorMaterRealVo.setOrderDate(orderDistributorMaterRealVo.getOrderDate());
				tOrderDistributorMaterRealVo.setOrderDay(orderDistributorMaterRealVo.getOrderDay());
				orderDistributorMaterRealVoList.add(tOrderDistributorMaterRealVo);
			}
			// 先判断 存在不存在此供货商的ordID

			// 往客户订单表中插入值
			// ordId =
			// selectFoodService.checkCommitMaterOrder(selectMaterVo.getOrderDate(),
			// shopId, 0);

			distributorService.addMaterOrderDetailForDistributor(orderDistributorMaterRealVoList, orderDistributorMaterRealVo.getOrdId());

			/*
			 * noteService.sendMessageToSup(String.valueOf(ordId),
			 * orderDistributorMaterRealVo.getOrderDate(),
			 * shopService.getShopPo(shopId) .getShopName());
			 */
			json1.put("success", true);
		} catch (Exception e) {
			log.info(e.toString());
			json1.put("success", false);
			json1.put("msg", e.getMessage());
		}
		return json1.toString();
	}

	/**
	 * @return
	 */
	@RequestMapping(value = "/findDistributorOrder.do")
	@ResponseBody
	public String findDistributorOrder(@RequestParam(required = false) String page, @RequestParam(required = false) String rows,
			OrderDistributorMaterRealVo orderDistributorMaterRealVo, HttpSession session) throws GenericException {
		JSONObject json = new JSONObject();
		log.info("----");
		if (page == null || page.equals(""))
			page = "1";
		if (rows == null || rows.equals(""))
			rows = "10";
		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));
		UserPo userInfo = (UserPo) session.getAttribute("user");
		// 根据用户id得出supid
		int ordDistributorId = supplierService.getSupIdByUserId(userInfo.getUserId());
		orderDistributorMaterRealVo.setOrdDistributorId(ordDistributorId);

		this.pageList = distributorService.listDistributorOrder(pageController, orderDistributorMaterRealVo);

		List<OrderDistributorMaterRealVo> orderDistributorMaterRealVoList = new ArrayList<OrderDistributorMaterRealVo>();
		List<OrderDistributorMaterRealVo> orderDistributorMaterRealVoListFooter = new ArrayList<OrderDistributorMaterRealVo>();
		BigDecimal ordValueReal = new BigDecimal(0);
		List items = pageList.getItems();
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				OrderDistributorMaterRealVo f = new OrderDistributorMaterRealVo();

				f.setOrdId((Integer) item[0]);
				f.setOrdSupId((Integer) item[1]);
				if (item[2] != null) {
					f.setOrdSupName((String) item[2]);
				} else {
					f.setOrdSupName("未设定");
				}
				f.setOrdStateDistributor((Integer) item[3]);
				f.setOrderDate((String) item[4]);
				f.setOrderDay((String) item[5]);
				if (item[6] != null) {
					f.setOrdValue(new BigDecimal(item[6].toString()));
					ordValueReal.add(new BigDecimal(item[6].toString()));
				} else {
					f.setOrdValue(new BigDecimal(0));
				}
				if (item[7] != null) {
					f.setOrdDescribe(item[7].toString());
				}

				orderDistributorMaterRealVoList.add(f);
			}
		}

		OrderDistributorMaterRealVo footer = new OrderDistributorMaterRealVo();
		footer.setOrdSupName("合计");
		footer.setOrdValue(ordValueReal);
		orderDistributorMaterRealVoListFooter.add(footer);
		json.put("footer", orderDistributorMaterRealVoListFooter);

		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", orderDistributorMaterRealVoList);
		log.info("----" + json.toString());
		return json.toString();
	}

	/**
	 * 进入供货商详细订单
	 * */
	@RequestMapping(value = "/goDistributorDetailed.do", method = { RequestMethod.GET })
	public ModelAndView goDistributorDetailed(int id, int supId, boolean flag, HttpSession session) {
		/*
		 * FoodVo foodVo = new FoodVo(); try {
		 * 
		 * foodVo = foodService.getFoodid(foodId); // 查询所有角色信息 } catch
		 * (GenericException e) { e.printStackTrace(); }
		 */
		Map map = new HashMap();
		/*
		 * map.put("ordId", id); map.put("supId", supId);
		 */

		try {
			UserPo userInfo = (UserPo) session.getAttribute("user");
			long ordDistributorId = supplierService.getSupIdByUserId(userInfo.getUserId());
			// 取得订单状态
			OrderDistributorVo tOrderDistributorVo = new OrderDistributorVo();
			tOrderDistributorVo.setOrdSupId(supId);
			tOrderDistributorVo.setOrdDistributorId(ordDistributorId);
			tOrderDistributorVo.setOrdId(id);

			OrderDistributorPo tOrderDistributorPo = distributorService.getOrderDistributorPo(tOrderDistributorVo);
			map.put("OrderDistributorPo", tOrderDistributorPo);
			if (flag) {
				return new ModelAndView("/distributor/distributorDetailedIndex", map);

			} else {
				return new ModelAndView("/distributor/distributorDetailedIndex_mobile", map);

			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ModelAndView("/base/error", map);
		}
	}

	/**
	 * @return
	 */
	@RequestMapping(value = "/findDistributorDetailOrder.do")
	@ResponseBody
	public String findDistributorDetailOrder(@RequestParam(required = false) String page, @RequestParam(required = false) String rows,
			OrderDistributorMaterRealVo orderDistributorMaterRealVo, HttpSession session) throws GenericException {
		JSONObject json = new JSONObject();
		if (page == null || page.equals(""))
			page = "1";

		// 设置rows 长度
		rows = "999";
		UserPo userInfo = (UserPo) session.getAttribute("user");
		// 根据用户id得出supid
		int ordDistributorId = supplierService.getSupIdByUserId(userInfo.getUserId());
		orderDistributorMaterRealVo.setOrdDistributorId(ordDistributorId);

		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));
		this.pageList = distributorService.findDistributorDetailOrder(pageController, orderDistributorMaterRealVo);
		List<OrderDistributorMaterRealVo> orderDistributorMaterRealVoList = new ArrayList<OrderDistributorMaterRealVo>();
		List items = pageList.getItems();

		BigDecimal ordValueRealAll = new BigDecimal(0);

		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				OrderDistributorMaterRealVo f = new OrderDistributorMaterRealVo();
				f.setOrdId(Integer.valueOf(item[0].toString()));
				f.setOrdDistributorMaterId(Integer.valueOf(item[1].toString()));
				f.setCode(item[2].toString());
				f.setOrdMaterId(Integer.valueOf(item[3].toString()));
				f.setMaterName(item[4].toString());
				f.setMaterType(Integer.valueOf(item[5].toString()));
				f.setBrands(item[6].toString());
				f.setSpecifications(item[7].toString());
				f.setUnit(item[8].toString());
				f.setOrdMaterLevel(Integer.valueOf(item[9].toString()));
				if (item[10] != null) {
					f.setOrdMaterValueUnit(new BigDecimal(item[10].toString()));
				} else {
					f.setOrdMaterValueUnit(new BigDecimal(0));
				}
				if (item[11] != null) {
					f.setOrdMaterValue(new BigDecimal(item[11].toString()));
				} else {
					f.setOrdMaterValue(new BigDecimal(0));
				}
				if (item[12] != null) {
					f.setOrdMaterWeight(new BigDecimal(item[12].toString()));
				} else {
					f.setOrdMaterWeight(new BigDecimal(0));
				}
				if (item[13] != null) {
					f.setOrdMaterWeightReality(new BigDecimal(item[13].toString()));
				} else {
					f.setOrdMaterWeightReality(new BigDecimal(0));
				}
				f.setOrdSupId(Integer.valueOf(item[14].toString()));
				if (item[15] != null) {
					f.setOrdSupName(item[15].toString());
				} else {
					f.setOrdSupName("未设定");
				}
				if (item[16] != null) {
					f.setOrdMaterValueLast(item[16].toString());
				} else {
					f.setOrdMaterValueLast("0");
				}
				orderDistributorMaterRealVoList.add(f);
			}
		}

		List<OrderSupplierMaterVoFooter> orderSupplierVoListFooter = new ArrayList<OrderSupplierMaterVoFooter>();
		OrderSupplierMaterVoFooter footer = new OrderSupplierMaterVoFooter();
		footer.setOrdCustName("合计");
		footer.setOrdMaterValueReal(ordValueRealAll);
		orderSupplierVoListFooter.add(footer);
		json.put("footer", orderSupplierVoListFooter);

		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", orderDistributorMaterRealVoList);
		return json.toString();
	}

	/**
	 * @return
	 */
	@RequestMapping(value = "/findDistributorDetailOrderForSup.do")
	@ResponseBody
	public String findDistributorDetailOrderForSup(@RequestParam(required = false) String page, @RequestParam(required = false) String rows,
			OrderDistributorMaterRealVo orderDistributorMaterRealVo, HttpSession session) throws GenericException {
		JSONObject json = new JSONObject();
		if (page == null || page.equals(""))
			page = "1";

		// 设置rows 长度
		rows = "999";
		UserPo userInfo = (UserPo) session.getAttribute("user");
		// 根据用户id得出supid
		int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
		orderDistributorMaterRealVo.setOrdSupId(supId);

		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));
		this.pageList = distributorService.findDistributorDetailOrderForSup(pageController, orderDistributorMaterRealVo);
		List<OrderDistributorMaterRealVo> orderDistributorMaterRealVoList = new ArrayList<OrderDistributorMaterRealVo>();
		List items = pageList.getItems();

		BigDecimal ordValueRealAll = new BigDecimal(0);

		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				OrderDistributorMaterRealVo f = new OrderDistributorMaterRealVo();
				f.setOrdId(Integer.valueOf(item[0].toString()));
				f.setOrdDistributorMaterId(Integer.valueOf(item[1].toString()));
				f.setCode(item[2].toString());
				f.setOrdMaterId(Integer.valueOf(item[3].toString()));
				f.setMaterName(item[4].toString());
				f.setMaterType(Integer.valueOf(item[5].toString()));
				f.setBrands(item[6].toString());
				f.setSpecifications(item[7].toString());
				f.setUnit(item[8].toString());
				f.setOrdMaterLevel(Integer.valueOf(item[9].toString()));
				if (item[10] != null) {
					f.setOrdMaterValueUnit(new BigDecimal(item[10].toString()));
				} else {
					f.setOrdMaterValueUnit(new BigDecimal(0));
				}
				if (item[11] != null) {
					f.setOrdMaterValue(new BigDecimal(item[11].toString()));
				} else {
					f.setOrdMaterValue(new BigDecimal(0));
				}
				if (item[12] != null) {
					f.setOrdMaterWeight(new BigDecimal(item[12].toString()));
				} else {
					f.setOrdMaterWeight(new BigDecimal(0));
				}
				if (item[13] != null) {
					f.setOrdMaterWeightReality(new BigDecimal(item[13].toString()));
				} else {
					f.setOrdMaterWeightReality(new BigDecimal(0));
				}
				f.setOrdSupId(Integer.valueOf(item[14].toString()));
				if (item[15] != null) {
					f.setOrdSupName(item[15].toString());
				} else {
					f.setOrdSupName("未设定");
				}
				if (item[16] != null) {
					f.setOrdMaterValueLast(item[16].toString());
				} else {
					f.setOrdMaterValueLast("0");
				}
				orderDistributorMaterRealVoList.add(f);
			}
		}

		List<OrderSupplierMaterVoFooter> orderSupplierVoListFooter = new ArrayList<OrderSupplierMaterVoFooter>();
		OrderSupplierMaterVoFooter footer = new OrderSupplierMaterVoFooter();
		footer.setOrdCustName("合计");
		footer.setOrdMaterValueReal(ordValueRealAll);
		orderSupplierVoListFooter.add(footer);
		json.put("footer", orderSupplierVoListFooter);

		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", orderDistributorMaterRealVoList);
		return json.toString();
	}

	// 导入价格和数量
	@RequestMapping(value = "/updateMaterWeightAndMaterValueForDistributor.do", method = { RequestMethod.POST })
	@ResponseBody
	public String updateMaterWeightAndMaterValueForDistributor(OrderDistributorMaterRealVo orderDistributorMaterRealVo, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws Exception {
		JSONObject json1 = new JSONObject();
		UserPo lgUser = (UserPo) session.getAttribute("user");
		int distributorId = supplierService.getSupIdByUserId(lgUser.getUserId());

		// 事物锁
		boolean lockFlag = lockTransService.lockTrans("updateMaterWeightAndMaterValueForDistributor.do", distributorId);
		if (!lockFlag) {
			json1.put("msg", "locked");
			json1.put("success", false);
			return json1.toString();
		}

		orderDistributorMaterRealVo.setOrdDistributorId(distributorId);
		boolean flag = false;
		try {
			OrderDistributorVo orderDistributorVo = new OrderDistributorVo();
			orderDistributorVo.setOrdDistributorId(distributorId);
			orderDistributorVo.setOrdId(orderDistributorMaterRealVo.getOrdId());
			orderDistributorVo.setOrdSupId(orderDistributorMaterRealVo.getOrdSupId());
			// 校验状态
			OrderDistributorPo orderDistributorPo = distributorService.getOrderDistributorPo(orderDistributorVo);

			if (orderDistributorPo.getOrdStateDistributor() == 1 || orderDistributorPo.getOrdStateDistributor() == 2) {
				distributorService.updateOrderForDistributor(orderDistributorMaterRealVo);
				// true 改变状态标记 改为2
				distributorService.updateOrderMaterValueAll(orderDistributorPo, true);
				json1.put("success", true);
			} else {
				json1.put("msg", "订单已被确认或者状态不正确！");
				json1.put("success", false);
			}
			// supplierService.computeTotalValue(materVo.getDate(),
			// materVo.getSupId());
		} catch (Exception e) {
			json1.put("msg", supplierService.getMsg());
			flag = false;
		} finally {
			// 解锁
			lockTransService.unlockTrans("updateMaterWeightAndMaterValueForDistributor.do", distributorId);
		}
		return json1.toString();
	}

	@RequestMapping(value = "/deleteDistributorOrderMater.do", method = { RequestMethod.POST })
	@ResponseBody
	public String deleteDistributorOrderMater(String jsonString, HttpSession session, OrderDistributorMaterRealVo orderDistributorMaterRealVo) {
		JSONObject json1 = new JSONObject();
		try {
			UserPo lgUser = (UserPo) session.getAttribute("user");
			int distributorId = supplierService.getSupIdByUserId(lgUser.getUserId());

			orderDistributorMaterRealVo.setOrdDistributorId(distributorId);

			OrderDistributorVo orderDistributorVo = new OrderDistributorVo();
			orderDistributorVo.setOrdDistributorId(distributorId);
			orderDistributorVo.setOrdId(orderDistributorMaterRealVo.getOrdId());
			orderDistributorVo.setOrdSupId(orderDistributorMaterRealVo.getOrdSupId());
			// 校验状态
			OrderDistributorPo orderDistributorPo = distributorService.getOrderDistributorPo(orderDistributorVo);

			if (orderDistributorPo.getOrdStateDistributor() == 1 || orderDistributorPo.getOrdStateDistributor() == 2) {
				distributorService.deleteOrderMaterForDistributor(orderDistributorMaterRealVo);

				json1.put("success", true);
			} else {
				json1.put("msg", "订单已被确认或者状态不正确！");
				json1.put("success", false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			json1.put("success", false);
			json1.put("msg", e.getMessage());
		}
		return json1.toString();
	}

	@RequestMapping(value = "/deleteDistributorOrder.do", method = { RequestMethod.POST })
	@ResponseBody
	public String deleteDistributorOrder(HttpSession session, OrderDistributorMaterRealVo orderDistributorMaterRealVo) {
		JSONObject json1 = new JSONObject();
		try {
			UserPo lgUser = (UserPo) session.getAttribute("user");
			int distributorId = supplierService.getSupIdByUserId(lgUser.getUserId());

			orderDistributorMaterRealVo.setOrdDistributorId(distributorId);

			OrderDistributorVo orderDistributorVo = new OrderDistributorVo();
			orderDistributorVo.setOrdDistributorId(distributorId);
			orderDistributorVo.setOrdId(orderDistributorMaterRealVo.getOrdId());
			orderDistributorVo.setOrdSupId(orderDistributorMaterRealVo.getOrdSupId());
			// 校验状态
			OrderDistributorPo orderDistributorPo = distributorService.getOrderDistributorPo(orderDistributorVo);

			if (orderDistributorPo.getOrdStateDistributor() == 1 || orderDistributorPo.getOrdStateDistributor() == 2) {
				distributorService.deleteOrderForDistributor(orderDistributorMaterRealVo);

				json1.put("success", true);
			} else {
				json1.put("msg", "订单已被确认或者状态不正确！");
				json1.put("success", false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			json1.put("success", false);
			json1.put("msg", e.getMessage());
		}
		return json1.toString();
	}

	@RequestMapping(value = "/reviewOrderDistributor.do", method = { RequestMethod.POST })
	@ResponseBody
	public String reviewOrderDistributor(String jsonString, HttpSession session, OrderDistributorMaterRealVo orderDistributorMaterRealVo) {
		JSONObject json1 = new JSONObject();
		try {
			UserPo lgUser = (UserPo) session.getAttribute("user");
			int distributorId = supplierService.getSupIdByUserId(lgUser.getUserId());

			orderDistributorMaterRealVo.setOrdDistributorId(distributorId);

			OrderDistributorVo orderDistributorVo = new OrderDistributorVo();
			orderDistributorVo.setOrdDistributorId(distributorId);
			orderDistributorVo.setOrdId(orderDistributorMaterRealVo.getOrdId());
			orderDistributorVo.setOrdSupId(orderDistributorMaterRealVo.getOrdSupId());
			// 校验状态
			OrderDistributorPo orderDistributorPo = distributorService.getOrderDistributorPo(orderDistributorVo);

			if (orderDistributorPo.getOrdSupId() == 0) {
				json1.put("msg", "未设定供货商！");
				json1.put("success", false);
				return json1.toString();
			}
			if (orderDistributorPo.getOrdStateDistributor() == 1 || orderDistributorPo.getOrdStateDistributor() == 2) {
				distributorService.reviewOrderDistributor(orderDistributorPo);
				// 产生入库单

				UserPo userInfo = (UserPo) session.getAttribute("user");
				int storeHouseId = storeService.getStoreHouseIdBySupId(distributorId);

				StoreInVo storeInVo = new StoreInVo();
				storeInVo.setStoreHouseId(storeHouseId);
				storeInVo.setStoreInState(1);// 状态未确认
				storeInVo.setStoreInWay(2);// 订单自动入库
				storeInVo.setOrdId(orderDistributorPo.getOrdId());
				storeInVo.setSupId(distributorId);// 供货商
				storeInVo.setSupSupId(orderDistributorMaterRealVo.getOrdSupId());
				storeInVo.setCreatDate(orderDistributorMaterRealVo.getOrderDate());

				StoreInPo storeInPo = storeService.addStoreInForSup(storeInVo);
				storeInVo.setStoreInId(storeInPo.getStoreInId());
				// 自动入库
				storeService.addStoreInDetailedForDistributor(storeInVo, storeInPo);

				json1.put("success", true);
			} else {
				json1.put("msg", "订单已被审核或者状态不正确！");
				json1.put("success", false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			json1.put("success", false);
			json1.put("msg", e.getMessage());
		}
		return json1.toString();
	}

	// 根据日期检索入库材料价格
	@RequestMapping(value = "/getMaterValueUnitFromOrderDistributorMaterRealPo.do", method = { RequestMethod.POST })
	@ResponseBody
	public String getMaterValueUnitFromOrderDistributorMaterRealPo(HttpSession session, HttpServletRequest request, HttpServletResponse response,
			OrderDistributorMaterRealVo tOrderDistributorMaterRealVo) {
		JSONObject json = new JSONObject();
		json.put("success", true);
		BigDecimal materValueCost = new BigDecimal(0);

		UserPo userInfo = (UserPo) session.getAttribute("user");
		BigDecimal materValueReal = new BigDecimal(0);
		try {

			int distributorId = supplierService.getSupIdByUserId(userInfo.getUserId());
			OrderDistributorMaterRealPo orderDistributorMaterRealPo = distributorService.getOrderDistributorMaterRealPo(tOrderDistributorMaterRealVo);
			if (orderDistributorMaterRealPo != null) {
				json.put("materValueCost", orderDistributorMaterRealPo.getOrdMaterValueUnit());
			} else {
				json.put("materValueCost", 0);
			}

		} catch (GenericException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json.toString();
	}

	// 批量导入 分销商订单
	@RequestMapping(value = "/importCommitMaterOrderForDistributor.do", method = { RequestMethod.POST })
	@ResponseBody
	public String importCommitMaterOrderForDistributor(ExcelVo excelVo, HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws Exception {

		JSONObject json1 = new JSONObject();
		// 事物锁
		UserPo lgUser = (UserPo) session.getAttribute("user");
		int distributorId = supplierService.getSupIdByUserId(lgUser.getUserId());
		boolean lockFlag = lockTransService.lockTrans("importCommitMaterOrderForDistributor.do", distributorId);
		if (!lockFlag) {
			json1.put("msg", "locked");
			json1.put("success", false);
			return json1.toString();
		}
		// 事务锁over
		try {

			MultipartFile filename = excelVo.getFilename();

			String temp = request.getSession().getServletContext().getRealPath(File.separator) + "temp"; // 临时目录
			File tempFile = new File(temp);
			if (!tempFile.exists()) {
				tempFile.mkdirs();
			}
			DiskFileUpload fu = new DiskFileUpload();
			fu.setSizeMax(10 * 1024 * 1024); // 设置允许用户上传文件大小,单位:位
			fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:位
			fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
			// 开始读取上传信息
			// int index = 0;
			if (filename == null)
				return null;

			String name = filename.getOriginalFilename();// 获取上传文件名,包括路径
			// name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
			long size = filename.getSize();
			if ((name == null || name.equals("")) && size == 0) {
				json1.put("msg", "文件为空！");
				json1.put("success", false);
				return json1.toString();
			}
			InputStream in = filename.getInputStream();

			ExcelReader excelReader = new ExcelReader();
			String[] title = excelReader.readExcelTitle(in);
			// System.out.println("获得Excel表格的标题:");
			/*
			 * for (String s : title) { System.out.print(s + " "); }
			 * 
			 * // 对读取Excel表格内容测试 Map<Integer, String> map =
			 * excelReader.readExcelContent(in, "*");
			 */
			boolean flag = false;
			try {
				// supplierService.importSupMaterValue(map,
				// excelVo.getCustIdAll());
				// long ordDistributorId =
				// supplierService.getSupIdByUserId(userInfo.getUserId());

				flag = distributorService.importCommitMaterOrderForDistributorToSup(excelReader, filename.getInputStream(), distributorId,
						excelVo.getOrdDate());
				// String[] everyline = map.get(1).split("\\*");
				// supplierService.computeTotalValue(everyline[4],
				// Integer.valueOf(new BigDecimal(everyline[2]).intValue()), 0);
			} catch (Exception e) {
				json1.put("msg", e);
				flag = false;
			}

			if (flag) {
				json1.put("success", true);
			} else {
				json1.put("msg", distributorService.getMsg());
				json1.put("success", false);
			}
		} catch (Exception e) {
			json1.put("msg", "exception");
			json1.put("success", false);
			return json1.toString();
		} finally {
			// 解锁
			lockTransService.unlockTrans("importCommitMaterOrderForDistributor.do", distributorId);
		}
		return json1.toString();

	}

	@RequestMapping(value = "/updateOrdSupId.do", method = { RequestMethod.POST })
	@ResponseBody
	public String updateOrdSupId(HttpSession session, OrderDistributorMaterRealVo orderDistributorMaterRealVo) {
		JSONObject json1 = new JSONObject();
		try {
			UserPo lgUser = (UserPo) session.getAttribute("user");
			int distributorId = supplierService.getSupIdByUserId(lgUser.getUserId());

			orderDistributorMaterRealVo.setOrdDistributorId(distributorId);

			OrderDistributorVo orderDistributorVo = new OrderDistributorVo();
			orderDistributorVo.setOrdDistributorId(distributorId);
			orderDistributorVo.setOrdId(orderDistributorMaterRealVo.getOrdId());
			// 校验状态
			OrderDistributorPo orderDistributorPo = distributorService.getOrderDistributorPo(orderDistributorVo);

			if (orderDistributorPo.getOrdSupId() != 0) {
				json1.put("msg", "已设定供货商！");
				json1.put("success", false);
			} else {
				orderDistributorPo.setOrdSupId(orderDistributorMaterRealVo.getOrdSupId());
				distributorService.updateOrderDistributorPo(orderDistributorPo);
				json1.put("success", true);
			}

		} catch (Exception e) {
			e.printStackTrace();
			json1.put("success", false);
			json1.put("msg", e.getMessage());
		}
		return json1.toString();
	}

	@RequestMapping(value = "/changeOrdMater.do", method = { RequestMethod.POST })
	@ResponseBody
	public String changeOrdMater(HttpSession session, HttpServletRequest request, HttpServletResponse response,
			OrderDistributorMaterRealVo orderDistributorMaterRealVo) {
		JSONObject json = new JSONObject();
		boolean flag = true;
		try {
			UserPo lgUser = (UserPo) session.getAttribute("user");
			int distributorId = supplierService.getSupIdByUserId(lgUser.getUserId());
			orderDistributorMaterRealVo.setOrdDistributorId(distributorId);

			// 校验订单状态
			OrderDistributorVo orderDistributorVo = new OrderDistributorVo();
			orderDistributorVo.setOrdDistributorId(distributorId);
			orderDistributorVo.setOrdId(orderDistributorMaterRealVo.getOrdId());

			// 校验状态
			OrderDistributorPo orderDistributorPo = distributorService.getOrderDistributorPo(orderDistributorVo);

			orderDistributorMaterRealVo.setOrdDate(orderDistributorPo.getOrdDate());
			if (orderDistributorPo.getOrdStateDistributor() == CommonType.ORD_STATE_DISTRIBUTOR_3) {
				json.put("msg", "订单已被确认，不能转换！");
				json.put("success", false);
			} else {
				if (!distributorService.changeOrdMater(orderDistributorMaterRealVo)) {
					json.put("msg", distributorService.getMsg());
					json.put("success", false);
				} else {
					json.put("success", true);
				}
			}

		} catch (GenericException e) {
			e.printStackTrace();
			json.put("success", false);
			return json.toString();
		}
		return json.toString();
	}

	@RequestMapping(value = "/preUpdateSelectMaterForDistributor.do", method = { RequestMethod.GET })
	public ModelAndView preUpdateSelectMaterForDistributor(OrderDistributorMaterRealVo orderDistributorMaterRealVo, HttpSession session) {

		Map map = new HashMap();

		UserPo lgUser = (UserPo) session.getAttribute("user");
		int distributorId;
		try {
			distributorId = supplierService.getSupIdByUserId(lgUser.getUserId());
			orderDistributorMaterRealVo.setOrdDistributorId(distributorId);

			// 校验订单状态
			OrderDistributorVo orderDistributorVo = new OrderDistributorVo();
			orderDistributorVo.setOrdDistributorId(distributorId);
			orderDistributorVo.setOrdId(orderDistributorMaterRealVo.getOrdId());
			// 校验状态
			OrderDistributorPo orderDistributorPo = distributorService.getOrderDistributorPo(orderDistributorVo);
			map.put("OrderDistributorPo", orderDistributorPo);
		} catch (GenericException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return new ModelAndView("/selectfood/selectMaterForDistributorForUpdate", map);

	}
}
